<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

// 表格数据加载状态
const tableLoading = ref(false);

// 优惠券列表数据
const couponList = ref([]);

// 搜索表单
const searchForm = reactive({
  keyword: '',
  type: '',
  status: '',
  dateRange: []
});

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 优惠券类型选项
const couponTypeOptions = [
  { label: '满减券', value: 'reduction' },
  { label: '折扣券', value: 'discount' },
  { label: '代金券', value: 'voucher' },
  { label: '礼品券', value: 'gift' }
];

// 状态选项
const statusOptions = [
  { label: '进行中', value: 'active' },
  { label: '未开始', value: 'inactive' },
  { label: '已结束', value: 'expired' },
  { label: '已停用', value: 'disabled' }
];

// 加载优惠券数据
const loadCouponData = () => {
  tableLoading.value = true;
  
  // 模拟API请求
  setTimeout(() => {
    // 生成模拟数据
    couponList.value = Array.from({ length: 20 }, (_, index) => {
      const id = index + 1;
      const typeIndex = Math.floor(Math.random() * 4);
      const statusIndex = Math.floor(Math.random() * 4);
      const now = new Date();
      const startDate = new Date(now.getTime() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000);
      const endDate = new Date(now.getTime() + Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000);
      
      // 根据类型生成不同的优惠信息
      let discountInfo = '';
      if (couponTypeOptions[typeIndex].value === 'reduction') {
        const threshold = Math.floor(Math.random() * 10) * 10 + 50;
        const amount = Math.floor(threshold / 2);
        discountInfo = `满${threshold}减${amount}`;
      } else if (couponTypeOptions[typeIndex].value === 'discount') {
        const discount = (Math.floor(Math.random() * 5) + 5) / 10;
        discountInfo = `${discount * 10}折`;
      } else if (couponTypeOptions[typeIndex].value === 'voucher') {
        const amount = Math.floor(Math.random() * 10) * 10 + 20;
        discountInfo = `${amount}元代金券`;
      } else {
        discountInfo = '礼品券';
      }
      
      return {
        id,
        name: `${couponTypeOptions[typeIndex].label}${id}`,
        type: couponTypeOptions[typeIndex].value,
        typeName: couponTypeOptions[typeIndex].label,
        discountInfo,
        description: `${couponTypeOptions[typeIndex].label}描述信息`,
        startDate: startDate.toLocaleDateString(),
        endDate: endDate.toLocaleDateString(),
        total: Math.floor(Math.random() * 900) + 100,
        used: Math.floor(Math.random() * 100),
        status: statusOptions[statusIndex].value,
        statusName: statusOptions[statusIndex].label,
        createTime: new Date(now.getTime() - Math.floor(Math.random() * 60) * 24 * 60 * 60 * 1000).toLocaleString()
      };
    });
    
    pagination.total = 112; // 模拟总数据量
    tableLoading.value = false;
  }, 1000);
};

// 处理页码变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page;
  loadCouponData();
};

// 处理每页条数变化
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  loadCouponData();
};

// 处理查询
const handleSearch = () => {
  pagination.currentPage = 1;
  loadCouponData();
};

// 重置查询条件
const resetSearch = () => {
  searchForm.keyword = '';
  searchForm.type = '';
  searchForm.status = '';
  searchForm.dateRange = [];
  
  pagination.currentPage = 1;
  loadCouponData();
};

// 查看优惠券详情
const viewCouponDetails = (row) => {
  ElMessage.info(`查看优惠券详情：${row.name}`);
};

// 编辑优惠券
const editCoupon = (row) => {
  ElMessage.info(`编辑优惠券：${row.name}`);
};

// 删除优惠券
const deleteCoupon = (row) => {
  ElMessageBox.confirm(`确定要删除优惠券"${row.name}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功');
    loadCouponData();
  }).catch(() => {});
};

// 发放优惠券
const issueCoupon = (row) => {
  ElMessage.info(`发放优惠券：${row.name}`);
};

// 停用/启用优惠券
const toggleCouponStatus = (row) => {
  const action = row.status === 'active' ? '停用' : '启用';
  
  ElMessageBox.confirm(`确定要${action}优惠券"${row.name}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success(`${action}成功`);
    row.status = row.status === 'active' ? 'disabled' : 'active';
    row.statusName = row.status === 'active' ? '进行中' : '已停用';
  }).catch(() => {});
};

// 初始化加载
onMounted(() => {
  loadCouponData();
});
</script>

<template>
  <div class="coupon-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>优惠券管理</h2>
    </div>
    
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="关键词">
          <el-input 
            v-model="searchForm.keyword" 
            placeholder="优惠券名称/描述"
            clearable
          />
        </el-form-item>
        <el-form-item label="优惠券类型">
          <el-select v-model="searchForm.type" placeholder="请选择" clearable>
            <el-option 
              v-for="item in couponTypeOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable>
            <el-option 
              v-for="item in statusOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="有效时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 表格区域 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <span>优惠券列表</span>
          <el-button type="primary">
            <el-icon><Plus /></el-icon>
            新增优惠券
          </el-button>
        </div>
      </template>
      
      <el-table 
        :data="couponList" 
        v-loading="tableLoading" 
        border 
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="name" label="优惠券名称" width="140" />
        <el-table-column prop="typeName" label="类型">
          <template #default="{ row }">
            <el-tag 
              :type="
                row.type === 'reduction' ? 'danger' : 
                row.type === 'discount' ? 'warning' : 
                row.type === 'voucher' ? 'success' : 'info'
              "
            >
              {{ row.typeName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="discountInfo" label="优惠信息" />
        <el-table-column label="有效期">
          <template #default="{ row }">
            {{ row.startDate }} 至 {{ row.endDate }}
          </template>
        </el-table-column>
        <el-table-column label="使用情况">
          <template #default="{ row }">
            {{ row.used }}/{{ row.total }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag 
              :type="
                row.status === 'active' ? 'success' : 
                row.status === 'inactive' ? 'info' : 
                row.status === 'expired' ? 'warning' : 'danger'
              "
            >
              {{ row.statusName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280">
          <template #default="{ row }">
            <el-button 
              size="small" 
              @click="viewCouponDetails(row)"
            >
              详情
            </el-button>
            <el-button 
              size="small" 
              type="primary" 
              @click="editCoupon(row)"
            >
              编辑
            </el-button>
            <el-button 
              size="small" 
              type="success" 
              @click="issueCoupon(row)"
            >
              发放
            </el-button>
            <el-button 
              v-if="row.status === 'active' || row.status === 'inactive'"
              size="small" 
              :type="row.status === 'active' ? 'warning' : 'success'" 
              @click="toggleCouponStatus(row)"
            >
              {{ row.status === 'active' ? '停用' : '启用' }}
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="deleteCoupon(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.coupon-container {
  padding: 20px;
}
.page-header {
  margin-bottom: 20px;
}
.search-card {
  margin-bottom: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 
